//
//  SceneViewController.m
//  Blue-toothLight
//
//  Created by mazg on 15/6/20.
//  Copyright (c) 2015年 mazg. All rights reserved.
//

#import "SceneViewController.h"
#import "DrawView.h"
#import "CustomColorModel.h"
#import "NSManagedObject+helper.h"
#import "UIImage+ColorAtPixel.h"
#import "UIImage+Tool.h"

#define WinWidth [UIScreen mainScreen].bounds.size.width
#define WinHeight [UIScreen mainScreen].bounds.size.height

#define W(x) WinWidth*x/320.0
#define H(y) WinHeight*y/568.0

@interface SceneViewController (){
    NSArray *uiColorArr;//界面上显示的一个个系统颜色信息
    NSArray *tmpLabelArr;//界面上显示的一个个系统颜色文字数组
    NSMutableArray *customColorModelArr;//数据库中所保存的自定义颜色信息
    UIView *currentView;//当前所操作的某个自定义的颜色
}

@end

@implementation SceneViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpInitalColor];//初始化系统颜色
    [self setUpInitalView];//初始化系统的view
    
    //初始化数据库中已经保存的颜色信息
    customColorModelArr=[[NSMutableArray alloc]init];
    NSArray *tmpArr= [CustomColorModel filter:nil orderby:nil offset:0 limit:0];
    [customColorModelArr addObjectsFromArray:tmpArr];
    [self setUpCustonColorView];
    
    //初始化编辑颜色的视图
    [self.view addSubview:self.customColorView];
    [self setupColorHiddenView];
}

//初始化原始界面视图(不包括自定义的颜色)
-(void)setUpInitalColor{
    tmpLabelArr=@[@"明亮",@"月光",@"阅读",@"冷冽",@"温暖",@"魅惑",@"渐变",@"快闪",@"慢闪"];
    
    UIColor *color1=[UIColor colorWithRed:216/255.0f green:208/255.0f blue:209/255.0f alpha:1.0f];
    NSArray *arr1=@[color1];
    UIColor *color2=[UIColor colorWithRed:23/255.0f green:34/255.0f blue:83/255.0f alpha:1.0f];
    NSArray *arr2=@[color2];
    UIColor *color3=[UIColor colorWithRed:221/255.0f green:163/255.0f blue:16/255.0f alpha:1.0f];
    NSArray *arr3=@[color3];
    UIColor *color4=[UIColor colorWithRed:54/255.0f green:195/255.0f blue:149/255.0f alpha:1.0f];
    NSArray *arr4=@[color4];
    UIColor *color5=[UIColor colorWithRed:195/255.0f green:91/255.0f blue:29/255.0f alpha:1.0f];
    NSArray *arr5=@[color5];
    UIColor *color6=[UIColor colorWithRed:186/255.0f green:47/255.0f blue:67/255.0f alpha:1.0f];
    NSArray *arr6=@[color6];
    
    
    UIColor *color11=[UIColor colorWithRed:254/255.0f green:244/255.0f blue:63/255.0f alpha:1.0f];
    UIColor *color12=[UIColor colorWithRed:245/255.0f green:0/255.0f blue:32/255.0f alpha:1.0f];
    UIColor *color13=[UIColor colorWithRed:232/255.0f green:0/255.0f blue:255/255.0f alpha:1.0f];
    NSArray *arr7=@[color11,color12,color13];
    
    
    UIColor *color21=[UIColor colorWithRed:199/255.0f green:0/255.0f blue:255/255.0f alpha:1.0f];
    UIColor *color22=[UIColor colorWithRed:101/255.0f green:0/255.0f blue:254/255.0f alpha:1.0f];
    UIColor *color23=[UIColor colorWithRed:32/255.0f green:40/255.0f blue:255/255.0f alpha:1.0f];
    UIColor *color24=[UIColor colorWithRed:252/255.0f green:255/255.0f blue:65/255.0f alpha:1.0f];
    UIColor *color25=[UIColor colorWithRed:157/255.0f green:5/255.0f blue:152/255.0f alpha:1.0f];
    UIColor *color26=[UIColor colorWithRed:59/255.0f green:255/255.0f blue:209/255.0f alpha:1.0f];
    UIColor *color27=[UIColor colorWithRed:59/255.0f green:254/255.0f blue:49/255.0f alpha:1.0f];
    UIColor *color28=[UIColor colorWithRed:46/255.0f green:105/255.0f blue:138/255.0f alpha:1.0f];
    NSArray *arr8=@[color21,color22,color23,color24,color25,color26,color27,color28];
    
    
    UIColor *color31=[UIColor colorWithRed:53/255.0f green:87/255.0f blue:249/255.0f alpha:1.0f];
    UIColor *color32=[UIColor colorWithRed:186/255.0f green:195/255.0f blue:231/255.0f alpha:1.0f];
    UIColor *color33=[UIColor colorWithRed:252/255.0f green:242/255.0f blue:258/255.0f alpha:1.0f];
    UIColor *color34=[UIColor colorWithRed:252/255.0f green:255/255.0f blue:65/255.0f alpha:1.0f];
    UIColor *color35=[UIColor colorWithRed:157/255.0f green:5/255.0f blue:152/255.0f alpha:1.0f];
    UIColor *color36=[UIColor colorWithRed:59/255.0f green:255/255.0f blue:209/255.0f alpha:1.0f];
    UIColor *color37=[UIColor colorWithRed:59/255.0f green:254/255.0f blue:49/255.0f alpha:1.0f];
    UIColor *color38=[UIColor colorWithRed:46/255.0f green:105/255.0f blue:138/255.0f alpha:1.0f];
    NSArray *arr9=@[color31,color32,color33,color34,color35,color36,color37,color38];
    
    uiColorArr=@[arr1,arr2,arr3,arr4,arr5,arr6,arr7,arr8,arr9];
}

//初始化原始界面视图(不包括自定义的颜色)
-(void)setUpInitalView{
    int row=3;
    int col=3;
    int orignX=0;
    int orignY=0;
    
    float KWidth=WinWidth/3.0f;
    float KHeight=KWidth;
    
    for (int i=0; i<row; i++) {
        for (int j=0; j<col; j++) {
            //1、大view
            UIView *tmp=[[UIView alloc]init];
            orignX=j*KWidth;
            orignY=H(80)+i*KHeight;
            tmp.frame=CGRectMake(orignX, orignY, KWidth, KHeight);
            tmp.tag=i*row+j;
            [self.view addSubview:tmp];
            
            //2、大view中添加了一个DrawView，用来显示颜色信息
            DrawView *imgView=[[DrawView alloc]initWithFrame:CGRectMake(tmp.frame.size.width/2.0-20, 30, 40, 20)];
            imgView.backgroundColor=[UIColor clearColor];
            imgView.colorArr=uiColorArr[i*row+j];
            imgView.layer.shadowOffset=CGSizeMake(-8, 8);
            imgView.layer.shadowOpacity=0.5;
            imgView.layer.shadowColor=[[uiColorArr[i*row+j] objectAtIndex:0] CGColor];
            [tmp addSubview:imgView];
            //3、大view中添加了一个label，用来显示颜色的文字信息
            UILabel *label=[[UILabel alloc]init];
            label.frame=CGRectMake(0, CGRectGetMaxY(imgView.frame)+15, tmp.frame.size.width, 30);
            label.text=tmpLabelArr[i*row+j];
            label.textAlignment=NSTextAlignmentCenter;
            label.textColor=[UIColor whiteColor];
            [tmp addSubview:label];
            //4、给大view添加一个手势
            UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapWithColor:)];
            [tmp addGestureRecognizer:tapGesture];
        }
    }
}


//设置自定义的视图
-(void)setUpCustonColorView{
    int col=3;
    
    float KWidth=WinWidth/3.0f;
    float KHeight=KWidth;
    
    for (int j=0; j<col; j++) {
        CustomColorModel *selModel;
        for (CustomColorModel *model in customColorModelArr) {
            if ([model.tag isEqual:[NSNumber numberWithInt:3*3+j]]) {
                selModel=model;
            }
        }
        
        UIView *tmp=[[UIView alloc]init];
        int orignX=j*KWidth;
        int orignY=H(80)+3*KHeight;;
        tmp.frame=CGRectMake(orignX, orignY, KWidth, KHeight);
        tmp.tag=3*3+j;
        [self.view addSubview:tmp];
        
        DrawView *imgView=[[DrawView alloc]initWithFrame:CGRectMake(tmp.frame.size.width/2.0-20, 30, 40, 20)];
        imgView.tag=1000;
        imgView.backgroundColor=[UIColor clearColor];
        imgView.layer.shadowOffset=CGSizeMake(-8, 8);
        imgView.layer.shadowOpacity=0.5;
        imgView.layer.shadowColor=[selModel.color CGColor];
        
        
        UILabel *label=[[UILabel alloc]init];
        label.tag=1001;
        label.frame=CGRectMake(0, CGRectGetMaxY(imgView.frame)+15, tmp.frame.size.width, 30);
        if (selModel) {
            label.text=selModel.name;
            NSLog(@"%@",selModel.name);
            
            imgView.colorArr=@[selModel.color];
        }
        else{
            label.text=@"长按编辑";
        }
        [tmp addSubview:imgView];
        
        label.textAlignment=NSTextAlignmentCenter;
        label.textColor=[UIColor whiteColor];
        [tmp addSubview:label];
        
        //添加轻击手势
        UITapGestureRecognizer *tapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doTapWithColor:)];
        [tmp addGestureRecognizer:tapGesture];
        
        //添加长按手势
        UILongPressGestureRecognizer *longGesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longGestureAction:)];
        longGesture.minimumPressDuration=0.5;
        [tmp addGestureRecognizer:longGesture];
    }
}

//初始化自定义颜色的仕途
-(void)setupColorHiddenView{
    UIImage *img=[UIImage imageWithName:@"pickerColorWheel@2x.png" border:5.0f borderColor:[UIColor lightGrayColor]];
    self.wheelcolorView=[[UIImageView alloc]initWithImage:img];
    self.wheelcolorView.center=CGPointMake(WinWidth/2.0f, self.customColorView.frame.size.height/2.0f);
    [self.customColorView addSubview:self.wheelcolorView];
    self.customColorView.hidden=YES;
}

//轻击手势的触摸方法
-(void)doTapWithColor:(UITapGestureRecognizer *)gesture{
    UIView *tapView=gesture.view;
    NSInteger tag=tapView.tag;
    NSMutableArray *selectedColorArr;
    if (tag<=8) {
        selectedColorArr=[uiColorArr[tag] mutableCopy];
    }
    NSArray *perArr=[self getCurrentPeripheralArr];
    switch (tag) {
            //颜色渐变
        case 6:
        {
            for (CBPeripheral *cbp in perArr) {
                [self.colorInstance changeColorWithPeripheral:cbp ToTargetWith_Jianbian:selectedColorArr];
            }
        }
            break;
           //颜色快闪
        case 7:
        {
            for (CBPeripheral *cbp in perArr) {
                [self.colorInstance changeColorWithPeripheral:cbp ToTargetWith_Kuaishan:selectedColorArr];
            }
        }
            break;
            //颜色慢闪
        case 8:
        {
            for (CBPeripheral *cbp in perArr) {
                [self.colorInstance changeColorWithPeripheral:cbp ToTargetWith_Manshan:selectedColorArr];
            }
        }
            break;
            //自定义颜色
        case 9:
        {
            [self tapCustomColorViewWithTag:@9];
        }
            break;
        case 10:
        {
            [self tapCustomColorViewWithTag:@10];
        }
            break;
        case 11:
        {
            [self tapCustomColorViewWithTag:@11];
        }
            break;
         
            //剩下的是默认状态
        default:
        {
            NSArray *selectedColorArr=uiColorArr[tag];
            UIColor *selectedColor=selectedColorArr[0];
            CGFloat r,g,b,a;
            [selectedColor getRed:&r green:&g blue:&b alpha:&a];
            UIColor *newColor=[UIColor colorWithRed:r green:g blue:b alpha:0];
            
            NSArray *perArr=[self getCurrentPeripheralArr];
            for (CBPeripheral *cbp in perArr) {
                [self.colorInstance changeColorWithPeripheral:cbp ToTarget:newColor];
            }
        }
        break;
     }
}

//触摸自定义的颜色视图的处理方法
-(void)tapCustomColorViewWithTag:(NSNumber *)tag{
    NSString *pre=[NSString stringWithFormat:@"tag='%@'",tag];
    NSArray *tmpArr=[CustomColorModel filter:pre orderby:nil offset:0 limit:0];
    if (tmpArr.count==0) {
        return;
    }
    UIColor *selectedColor=[tmpArr[0] color];
    CGFloat r,g,b,a;
    [selectedColor getRed:&r green:&g blue:&b alpha:&a];
    UIColor *newColor=[UIColor colorWithRed:r green:g blue:b alpha:0];
    
    NSArray *perArr=[self getCurrentPeripheralArr];
    for (CBPeripheral *cbp in perArr) {
        [self.colorInstance changeColorWithPeripheral:cbp ToTarget:newColor];
    }
}

//长按手势的触摸方法
-(void)longGestureAction:(UILongPressGestureRecognizer *)ges{
    if (ges.state == UIGestureRecognizerStateBegan) {
        UIView *tapView=ges.view;
        currentView=tapView;
        self.customColorView.hidden=NO;
    }
}


//触摸开始
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch* touch = [touches anyObject];
    [self getNewColorWithTouch:touch];
    [self.view endEditing:YES];
}

//得到手指触摸点所对应对颜色
-(BOOL )getNewColorWithTouch:(UITouch *)touch{
    //1、判断触摸点是否在圆形区域内
    CGPoint viewPoint=[touch locationInView:self.view];
    CGFloat raidus=self.wheelcolorView.frame.size.width/2.0f-5;
    if (![self pointInCircleRect:viewPoint radius:raidus]) {
        return NO;
    }
    _colorSlider.enabled=YES;
    //2、获取手指触摸点的颜色信息，这里－5是因为colorView中的真正图片外面包了5个像素点的颜色值
    CGPoint point = [touch locationInView:_wheelcolorView];
    point.x-=5;
    point.y-=5;
    UIImage *img=[UIImage imageNamed:@"pickerColorWheel@2x.png"];
    self.selColor=[img colorAtPixel:point];
    
    CGFloat r,g,b,a;
    [self.selColor getRed:&r green:&g blue:&b alpha:&a];

    if (r==0 && g==0 &&b==0) {
        return NO;
    }
    
    //3、改变所获取的颜色值的aplpa，得到一个新的颜色,更新imgView的边框圆颜色
    r=r*255.0f;
    g=g*255.0f;
    b=b*255.0f;
    a=_colorSlider.value;
    
    self.selColor=[UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a/255.0f];
    UIImage *newImg=[UIImage imageWithName:@"pickerColorWheel@2x.png" border:5.0f borderColor:[UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:(a/255.0f)]];
    _wheelcolorView.image=newImg;
    return YES;
}


//判断触摸点是否在圆形区域内
-(BOOL)pointInCircleRect:(CGPoint)point radius:(CGFloat)r{
    
    CGPoint newP=[self.view convertPoint:point toView:_customColorView];
    CGPoint center=_wheelcolorView.center;
    int spaceX=newP.x-center.x;
    int spaceY=newP.y-center.y;
    CGFloat f=sqrt(spaceX*spaceX+spaceY*spaceY);
    if (f<r) {
        return YES;
    }
    else{
        return NO;
    }
    return NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.colorInstance.alwaysChange=NO;
    self.selColor=nil;
}

//滑块变动后的处理方法
- (IBAction)sliderChanged:(id)sender {
    UISlider *slider=sender;
    CGFloat r,g,b,a;
    [self.selColor getRed:&r green:&g blue:&b alpha:&a];
    r=r*255.0f;
    g=g*255.0f;
    b=b*255.0f;
    a=a*255.0f;

    a=slider.value;
    
    self.selColor=[UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a/255.0f];
    UIImage *newImg=[UIImage imageWithName:@"pickerColorWheel@2x.png" border:5.0f borderColor:[UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:(a/255.0f)]];
    _wheelcolorView.image=newImg;
}

//点击完成按钮后的处理方法
- (IBAction)doColor:(id)sender {
    
    [self.view endEditing:YES];
    
    NSInteger tag=currentView.tag;
    NSString *pre=[NSString stringWithFormat:@"tag='%@'",[NSNumber numberWithInteger:tag]];
    NSArray *tmpArr=[CustomColorModel filter:pre orderby:nil offset:0 limit:0];
    CustomColorModel *model;
    if (tmpArr.count==0) {
        model=[CustomColorModel createNew];
    }
    else{
        model=tmpArr[0];
    }
    model.tag=[NSNumber numberWithInteger:tag];
    model.name=self.inputTextField.text;
    [CustomColorModel save:^(NSError *error) {
        
    }];
    if (self.selColor) {
        model.color=self.selColor;
        [CustomColorModel save:^(NSError *error) {
            
        }];
    }
    else{
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"请设置颜色" message:nil delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
        return;
    }
    
    DrawView *imgview=(DrawView *)[currentView viewWithTag:1000];
    imgview.colorArr=@[model.color];
    [imgview setNeedsDisplay];
    
    UILabel *label=(UILabel *)[currentView viewWithTag:1001];
    label.text=model.name;
    
    self.customColorView.hidden=YES;
    self.selColor=nil;
}

#pragma mark UITextFieldDelegate
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    textField.text=@"";
    textField.returnKeyType=UIReturnKeyDone;
    return YES;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self doColor:nil];
    return YES;
}
@end
